package com.luhan.fmmall.service.impl;


import com.luhan.fmmall.dao.OrderItemMapper;
import com.luhan.fmmall.dao.OrdersMapper;
import com.luhan.fmmall.dao.ProductSkuMapper;
import com.luhan.fmmall.dao.ShoppingCartMapper;
import com.luhan.fmmall.entity.*;
import com.luhan.fmmall.service.OrderService;
import com.luhan.fmmall.utils.PageHelper;
import com.luhan.fmmall.vo.ResStatus;
import com.luhan.fmmall.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private ProductSkuMapper productSkuMapper;

    /**
     * 保存订单业务
     * @param cids
     * @param order
     * @return
     */
    @Override
    @Transactional
    public Map<String,String> addOrder(String cids, Orders order) throws SQLException {
        HashMap<String,String> map = new HashMap<>();

        //1.校验库存：根据cids查询当前订单中关联购物车记录详情（包括库存）
        String[] arr = cids.split(",");
        List<Integer> cidsList = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            cidsList.add(Integer.parseInt(arr[i]));
        }
        List<ShoppingCartVO> list = shoppingCartMapper.selectShopCartByCids(cidsList);

        boolean f = true;
        String untitle = "";
        for (ShoppingCartVO sc : list) {
            if (Integer.parseInt(sc.getCartNum())>sc.getSkuStock()){
                f = false;
            }
            //根据所有商品名称，以，分割拼成字符串
            untitle = untitle + sc.getProductName()+",";
        }

        if (f){
            //2.保存订单
            order.setUntitled(untitle);
            order.setCreateTime(new Date());
            order.setStatus("1");
            //生成订单编号
            String orderId = UUID.randomUUID().toString().replace("-", "");
            order.setOrderId(orderId);
            int i = ordersMapper.insert(order);



            //3.生成商品快照
            for(ShoppingCartVO sc : list){
                int cnum = Integer.parseInt(sc.getCartNum());
                String itemId = System.currentTimeMillis()+""+(new Random().nextInt(89999)+10000);
                //保存订单快照
                OrderItem orderItem = new OrderItem(itemId, orderId, sc.getProductId(), sc.getProductName(), sc.getProductImg(), sc.getSkuId(),
                        sc.getSkuName(), new BigDecimal(sc.getSellPrice()), cnum, new BigDecimal(sc.getSellPrice() * cnum)
                        , new Date(), new Date(), 0);
                int m = orderItemMapper.insert(orderItem);
            }

            //4.扣减库存 根据套餐id修改套餐的库存量
            for(ShoppingCartVO sc : list){
                String skuId = sc.getSkuId();
                int newStock = sc.getSkuStock() - Integer.parseInt(sc.getCartNum());

                ProductSku productSku = new ProductSku();
                productSku.setSkuId(skuId);
                productSku.setStock(newStock);
                int n = productSkuMapper.updateByPrimaryKeySelective(productSku);
            }

            //5.删除购物车：当购物车中的记录购买成功之后，购物车中做对应的删除
            for(int cid : cidsList){
                int k = shoppingCartMapper.deleteByPrimaryKey(cid);
            }

            map.put("orderId",orderId);
            map.put("productNames",untitle);
            return map;
        }else {
            return null;
        }

    }

    @Override
    public int updateOrderStatus(String orderId, String status) {
        Orders orders = new Orders();
        orders.setOrderId(orderId);
        orders.setStatus(status);
        int i = ordersMapper.updateByPrimaryKeySelective(orders);
        return i;
    }

    @Transactional(isolation = Isolation.SERIALIZABLE)
    @Override
    public void closeOrder(String orderId) {
        //b.修改当前订单 已关闭status=6 关闭类型为超时未支付closeType=1
        Orders closeOrder = new Orders();
        closeOrder.setOrderId(orderId);
        closeOrder.setStatus("6");//已关闭
        closeOrder.setCloseType(1);//关闭类型
        ordersMapper.updateByPrimaryKeySelective(closeOrder);
        //c.还原库存：先根据当前订单编号查询商品快照（sku_id buu_count）-->修改product_sku_id
        //查询快照表获取购买数量
        Example example1 = new Example(OrderItem.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("orderId",orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example1);
        //还原库存（可能多个商品）
        for (int j = 0; j < orderItems.size(); j++) {
            OrderItem orderItem = orderItems.get(j);
            //修改
            ProductSku productSku = productSkuMapper.selectByPrimaryKey(orderItem.getSkuId());
            productSku.setStock(productSku.getStock()+orderItem.getBuyCounts());
            productSkuMapper.updateByPrimaryKeySelective(productSku);
        }
    }

    @Override
    public ResultVO listOrder(String userId, int pageNum, int limit, String status) {
        //1.分页查询
        int start = (pageNum-1)*limit;
        List<OrdersVO> list = ordersMapper.selectOrders(userId, status, start,limit);
        //2.计算总页数
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        if (status!=null&&!"".equals(status)){
            criteria.andEqualTo("status",status);
        }
        //总记录数
        int count = ordersMapper.selectCountByExample(example);
        //计算总页数
        int pageCount = count%limit==0?count/limit:count/limit+1;

        PageHelper<OrdersVO> pageHelper = new PageHelper<>(count,pageCount,list);
        return new ResultVO(ResStatus.OK, "success", pageHelper);
    }
}
